package com.zhoufy.service;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA by ChouFy on 2020-04-18.
 *
 * @author chouFy
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;

    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {

        System.out.println("decode finish 1");

        byte[] bytes = new byte[in.readableBytes()];
        in.readBytes(bytes);
        System.out.println("decode finish 2");

        try {
            Object deserialize = serializer.deserialize(clazz, bytes);
            out.add(deserialize);

            System.out.println("decode finish 3");

        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("decode finish 4");
    }

}
